package utils;

import dao.DocumentDAO;
import model.Document;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class CleanerUtil {
    private DocumentDAO documentDAO;

    public CleanerUtil() {
        documentDAO = new DocumentDAO();
    }

    private void scanDocuments() {
        List<Document> documents = documentDAO.getAllDocuments();
        for (int i = 0; i < documents.size(); i++) {
            if (documents.get(i).getStorageLife() != -1 && documents.get(i).getStorageLife() != 0) {
                if(documents.get(i).getDeleteDate() != null) {
                    documents.get(i).setDeleteDate(DateUtil.addDays(documents.get(i).getDeleteDate(), documents.get(i).getStorageLife()));
                }
                else {
                    documents.get(i).setDeleteDate(DateUtil.addDays(documents.get(i).getDate(), documents.get(i).getStorageLife()));
                }
                documents.get(i).setStorageLife(-1);
                documentDAO.updateDocument(documents.get(i));
            }
        }
    }

    private void deleteDocuments() throws IOException {
        List<Document> documents = documentDAO.getAllDocuments();
        for (int i = 0; i < documents.size(); i++) {
            if (documents.get(i).getDeleteDate() != null && documents.get(i).getDeleteDate().compareTo(new Date()) <= 0) {
                File file = new File("D:\\FILES\\" + documents.get(i).getIdDocument());
                file.delete();
                documentDAO.deleteDocumentById(documents.get(i).getIdDocument());
            }
        }
    }

    public void clean() throws Exception {
        scanDocuments();
        deleteDocuments();
    }
}
